/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mutualdocsserver;

import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;

/*
 * A chat server that delivers public and private messages.
 */
public class MutualDocsServer {

  // The server socket.
  private static ServerSocket serverSocket = null;
  // The client socket.
  private static Socket clientSocket = null;

 
 
  
  private static final int MaximoClientes = 10;
  private static final clientThread[] threads = new clientThread[MaximoClientes];

  public static void main(String args[]) {

    // Porta padrao
    int portNumber = 2222;
    if (args.length < 1) {

      System.out.println("MultiThreadServer <portNumber>\n"+ "Usando porta=" + portNumber);

    } else {
      portNumber = Integer.valueOf(args[0]).intValue();
    }

    /*
     * Open a server socket on the portNumber (default 2222). Note that we can
     * not choose a port less than 1023 if we are not privileged users (root).
     */
    try {
      serverSocket = new ServerSocket(portNumber);
    } catch (IOException e) {
      System.out.println(e);
    }

    /*
     * Create a client socket for each connection and pass it to a new client
     * thread.
     */
    while (true) {
      try {
        clientSocket = serverSocket.accept();
        int i = 0;
        for (i = 0; i < MaximoClientes; i++) {
          if (threads[i] == null) {
            (threads[i] = new clientThread(clientSocket, threads)).start();
            break;
          }
        }
        if (i == MaximoClientes) {
          PrintStream os = new PrintStream(clientSocket.getOutputStream());
          os.println("Servidor lotado.");
          os.close();
          clientSocket.close();
        }
      } catch (IOException e) {
        System.out.println(e);
      }
    }
  }
}

/*thread para os clientes */
class clientThread extends Thread {

  private DataInputStream imputst = null;
  private PrintStream outputst = null;
  private Socket clientSocket = null;
  private final clientThread[] threads;
  private int maxClientsCount;

  public clientThread(Socket clientSocket, clientThread[] threads) {
    this.clientSocket = clientSocket;
    this.threads = threads;
    maxClientsCount = threads.length;
  }

  public void run() {
    int maxClientsCount = this.maxClientsCount;
    clientThread[] threads = this.threads;

    try {
      /*
       * Create input and output streams for this client.
       */
      imputst = new DataInputStream(clientSocket.getInputStream());
      outputst = new PrintStream(clientSocket.getOutputStream());
      outputst.println("Enter your name.");
      String name = imputst.readLine().trim();
     // outputst.println("Hello " + name + " to our chat room.\nTo leave enter /quit in a new line");
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] != null && threads[i] != this) {
         //threads[i].outputst.println("*** A new user " + name + " entered the chat room !!! ***");
        }
      }
      while (true) {
        String line = imputst.readLine();
        if (line.startsWith("/quit")) {
          break;
        }
        for (int i = 0; i < maxClientsCount; i++) {
          if (threads[i] != null) {
            threads[i].outputst.println("<" + name + "&gr; " + line);
          }
        }
      }
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] != null && threads[i] != this) {
          threads[i].outputst.println("*** The user " + name + " is leaving the chat room !!! ***");
        }
      }
      outputst.println("*** Bye " + name + " ***");

      /*
       * Clean up. Set the current thread variable to null so that a new client
       * could be accepted by the server.
       */
      for (int i = 0; i < maxClientsCount; i++) {
        if (threads[i] == this) {
          threads[i] = null;
        }
      }

      /*
       * Close the output stream, close the input stream, close the socket.
       */
      imputst.close();
      outputst.close();
      clientSocket.close();
    } catch (IOException e) {
    }
  }
}